package com.sxkf.template.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxkf.core.third.im.entity.AddFriend;
import com.sxkf.core.third.im.service.YxService;
import com.sxkf.template.entity.*;
import com.sxkf.template.mapper.StoreMapper;
import com.sxkf.template.mapper.UserLikeMapper;
import com.sxkf.template.mapper.UserMapper;
import com.sxkf.template.service.FriendUserService;
import com.sxkf.template.service.UserLikeService;
import org.jeecg.common.exception.SxkfException;
import org.jeecg.common.util.CheckEmptyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户喜欢用户记录 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2024-08-20 11:48:58
 */
@Service
public class UserLikeServiceImpl extends ServiceImpl<UserLikeMapper, UserLike> implements UserLikeService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private YxService yxService;
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private FriendUserService friendUserService;

    @Override
    public void add(UserLike userLike) {

        if (CheckEmptyUtil.isEmpty(userLike.getLikeUserId())){
            throw new SxkfException("错误！关注用户id为空");
        }

        if (CheckEmptyUtil.isNotEmpty(userLike.getStoreId())){
            throw new SxkfException("错误！不能输入商店");
        }

        if (Objects.equals(userLike.getUserId(),userLike.getLikeUserId())){
            throw new SxkfException("不能关注自己");
        }

        UserLike one = getOne(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, userLike.getUserId()).eq(UserLike::getLikeUserId, userLike.getLikeUserId()));
        //如果已有点赞记录则取消点赞
        if (one != null){
            userMapper.reduceFansCount(userLike.getLikeUserId());
            userMapper.addFansCount(userLike.getUserId());

            //查看是否为互相关注，如果互相关注则移除好友关系
            long count = count(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, userLike.getLikeUserId()).eq(UserLike::getLikeUserId, userLike.getUserId()));
            if (count>0){
//                User user = userMapper.selectById(userLike.getUserId());
//                User likeUser = userMapper.selectById(userLike.getLikeUserId());
//                Boolean result = yxService.removeFriend(user.getPhone(), likeUser.getPhone());
                Boolean result = yxService.removeFriend(userLike.getUserId(),userLike.getLikeUserId());
                if (!result){
                    log.error("删除好友失败");
                }
//                friendUserService.deleteFriend(userLike.getUserId(),userLike.getLikeUserId());

            }
            removeById(one);
            return;
        }
        //如果未点赞则进行点赞
        save(userLike);

        userMapper.addFansCount(userLike.getLikeUserId());
        userMapper.reduceFansCount(userLike.getUserId());

        //查看是否为互相关注，如果互相关注则加好友
        long count = count(new LambdaQueryWrapper<UserLike>().eq(UserLike::getUserId, userLike.getLikeUserId()).eq(UserLike::getLikeUserId, userLike.getUserId()));
        if (count>0){
            User user = userMapper.selectById(userLike.getUserId());
            User likeUser = userMapper.selectById(userLike.getLikeUserId());
            AddFriend addFriend = new AddFriend();
            addFriend.setAccount_id(userLike.getUserId());
            addFriend.setFriend_account_id(userLike.getLikeUserId());
//            addFriend.setAccount_id(user.getPhone());
//            addFriend.setFriend_account_id(likeUser.getPhone());
            addFriend.setAlias(likeUser.getNickName());
            Boolean result = yxService.addFriend(1, addFriend);
            if (!result){
                log.error("添加好友失败");
            }
//            FriendUser friendUser = new FriendUser();
//            friendUser.setUserId(userLike.getUserId());
//            friendUser.setFriendId(userLike.getLikeUserId());
//            friendUserService.agreeFriend(friendUser);
        }
    }

    @Override
    public IPage<User> pageUser(Integer pageNo, Integer pageSize, String userId, String sortType) {
        Page<UserLike> page = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userId)
                .isNotNull(UserLike::getLikeUserId)
                .orderByDesc("1".equals(sortType),UserLike::getCreateTime)
                .orderByAsc("2".equals(sortType),UserLike::getCreateTime)
        );
        if (page.getRecords().isEmpty()){
            return new Page<>();
        }
        List<UserLike> records = page.getRecords();
        List<String> userIds = records.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        Map<String, Date> likeDateMap = records.stream().collect(Collectors.toMap(UserLike::getLikeUserId, UserLike::getCreateTime));

        List<User> users = userMapper.selectBatchIds(userIds);
        users.forEach(item-> item.setCreateTime(likeDateMap.get(item.getId())));
        Page<User> result = new Page<>(pageNo, pageSize, page.getTotal(), page.searchCount());
        result.setRecords(users);
        return result;
    }

    @Override
    public IPage<Store> pageStore(Integer pageNo, Integer pageSize, String userId, String sortType) {
        Page<UserLike> page = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userId)
                .isNotNull(UserLike::getStoreId)
                .orderByDesc("1".equals(sortType),UserLike::getCreateTime)
                .orderByAsc("2".equals(sortType),UserLike::getCreateTime)
        );
        if (page.getRecords().isEmpty()){
            return new Page<>();
        }
        List<UserLike> records = page.getRecords();

        List<String> storeIds = records.stream().map(UserLike::getStoreId).collect(Collectors.toList());
        Map<String, Date> likeDateMap = records.stream().collect(Collectors.toMap(UserLike::getStoreId, UserLike::getCreateTime));

        List<Store> storeList = storeMapper.selectBatchIds(storeIds);
        storeList.forEach(item-> item.setLikeTime(likeDateMap.get(item.getId())));

        Page<Store> result = new Page<>(pageNo, pageSize, page.getTotal(), page.searchCount());
        result.setRecords(storeList);
        return result;
    }

    @Override
    public IPage<User> pageFans(Integer pageNo, Integer pageSize, String userId, String sortType) {
        Page<UserLike> page = page(new Page<>(pageNo, pageSize), new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getLikeUserId, userId)
                .orderByDesc("1".equals(sortType),UserLike::getCreateTime)
                .orderByAsc("2".equals(sortType),UserLike::getCreateTime)
        );
        if (page.getRecords().isEmpty()){
            return new Page<>();
        }
        List<UserLike> records = page.getRecords();
        List<String> userIds = records.stream().map(UserLike::getUserId).collect(Collectors.toList());
        Map<String, Date> likeDateMap = records.stream().collect(Collectors.toMap(UserLike::getUserId, UserLike::getCreateTime));
        // 用于检查是否互关
        List<UserLike> userLikeList = list(new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userId)
                .in(UserLike::getLikeUserId, userIds));
        // 互关粉丝id
        List<String> likeUserList = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());

        List<User> users = userMapper.selectBatchIds(userIds);
        users.forEach(item-> {
//            item.setCreateTime(likeDateMap.get(item.getId()));
            item.setLikeTime(likeDateMap.get(item.getId()));
            if (likeUserList.contains(item.getId())){
                item.setIsEach("1");
            }else {
                item.setIsEach("0");
            }


        });
        Page<User> result = new Page<>(pageNo, pageSize, page.getTotal(), page.searchCount());
        result.setRecords(users);
        return result;
    }

    @Override
    public IPage<User> pageFriend(Integer pageNo, Integer pageSize, String userId){
        IPage<UserLike> page = baseMapper.findFriend(new Page<>(pageNo, pageSize), userId);
        if (page.getRecords().isEmpty()){
            return new Page<>();
        }
        List<UserLike> records = page.getRecords();
        List<String> userIds = records.stream().map(UserLike::getUserId).collect(Collectors.toList());

        List<User> users = userMapper.selectBatchIds(userIds);
        Page<User> result = new Page<>(pageNo, pageSize, page.getTotal(), page.searchCount());
        result.setRecords(users);
        return result;
    }

    @Override
    public void addStore(UserLike userLike) {

        if (CheckEmptyUtil.isEmpty(userLike.getUserId())){
            throw new SxkfException("错误！关注用户id为空");
        }

        if (CheckEmptyUtil.isNotEmpty(userLike.getLikeUserId())){
            throw new SxkfException("错误！不能输入被关注用户");
        }

        UserLike one = getOne(new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userLike.getUserId())
                .eq(UserLike::getStoreId, userLike.getStoreId()));
        //如果已有点赞记录则取消点赞
        if (one != null){
            removeById(one);
            storeMapper.update(null,new LambdaUpdateWrapper<Store>()
                    .setSql("fans_count = fans_count - 1")
                    .eq(Store::getId, one.getStoreId()));
            return;
        }

        //如果未点赞则进行点赞
        save(userLike);

        //帖子点赞量+1
        storeMapper.update(null,new LambdaUpdateWrapper<Store>()
                .setSql("fans_count = fans_count + 1")
                .eq(Store::getId, userLike.getStoreId()));


        return;
    }

    @Override
    public Boolean isLikeUser(String userId, String isLikeUser) {
        UserLike one = getOne(new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userId)
                .eq(UserLike::getLikeUserId, isLikeUser)
        );
        return !CheckEmptyUtil.isEmpty(one);
    }

    @Override
    public Boolean isLikeStore(String userId, String storeId) {
        UserLike one = getOne(new LambdaQueryWrapper<UserLike>()
                .eq(UserLike::getUserId, userId)
                .eq(UserLike::getStoreId, storeId)
        );
        return !CheckEmptyUtil.isEmpty(one);
    }
}
